<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

use app\admin\model\AdminUsers as Users;

class Login extends Controller
{
  /**
   * get admin/Login/index
   * 登录视图
   * @return view
   */
   public function index()
    {
        return view();
    }

    /**
     * post admin/Login/login
     * 登录信息检验
     * @return json array()
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $result = [];
            $data['key']      =  input("post.username");
            $data['password'] =  encrypt_pass(input("post.password"));
            $captcha          =  input("post.captcha");

            // 比对验证码
            if(!captcha_check($captcha)){
                $result = ['state'=>false,'errorCode'=>1,'msg'=>"验证码错误"];
            }else {
            // 比对密码
            $userModel = new Users();
            $userInfo  = $userModel->checkUserInfo($data);

            if( empty($userInfo) ){
                    $result = ['state'=>false,'errorCode'=>2,'msg'=>"用户或密码错误"];
            }else{
                if($userInfo->status){
                    //保存用户信息和登录凭证
                    session('admin_user_key',$data['key']);
                    session('admin_user_id',$userInfo->id);
                    session('admin_user_name',$userInfo->name);
                    session('login_count',$userInfo->login_count);
                    session('last_login_time',$userInfo->last_login_time);
                    session('last_login_ip',$userInfo->last_login_ip);
                    //更新用户数据
                    $userModel->updateLogin($userInfo->id,get_client_ip());

                    $result = ['state'=>true,'errorCode'=>0,'msg'=>"登录成功",'url'=>url('admin/Home/index')];
                }else{
                    $result = ['state'=>false,'errorCode'=>3,'msg'=>"用户已被封禁，请联系管理员"];
                }
            }

            unset($userModel); 
            unset($userInfo);

        }

        unset($data);
        unset($captcha);

        return json($result);
        }

    }

    /**
     * get admin/Login/loginOut
     * 退出登录
     * @return json array()
     */
    public function loginOut()
    {
       // 清除tag:admin_cache_data标签的缓存数据
        \think\Cache::clear('admin_cache_data');

        \think\Session::clear();
        return $this->error('','index/Index/index');
    }

}
